﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using K9Nano.AspNetCore.Filters;
using K9Nano.Captcha;
using K9Nano.Captcha.Sms;
using K9Nano.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace K9Nano.AspNetCore.Controllers;

[Produces("application/json")]
[ApiController]
[Route("api/captcha")]
public class CaptchaController(IOptions<K9Options> optionAccessor) : ControllerBase
{
    /// <summary>
    /// 获取图片验证码
    /// </summary>
    /// <param name="requestId"></param>
    /// <param name="captchaManager"></param>
    /// <returns></returns>
    [HttpGet("png/{requestId:required}")]
    public virtual CaptchaInfo GetCaptchaImage(string requestId, [FromServices] ICaptchaManager captchaManager)
    {
        if (string.IsNullOrEmpty(requestId))
        {
            throw FriendlyException.BadRequest("请求ID无效");
        }

        var captchaInfo = captchaManager.GenerateImage(requestId!,
            TimeSpan.FromMinutes(optionAccessor.Value.CaptchaExpires),
            optionAccessor.Value.CaptchaLength);
        return captchaInfo;
    }

    /// <summary>
    /// 发送短信验证码
    /// </summary>
    /// <param name="phone"></param>
    /// <param name="templateId"></param>
    /// <param name="code"></param>
    /// <returns></returns>
    [HttpGet("sms/template/{templateId:required}/{phone:required}/code/{code:required}")]
    public async virtual Task<ApiResponse> GetSmsCode(string phone,
        string templateId,
        string code)
    {
        // code: 图片验证码
        if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(code))
        {
            return ApiResponse.BadRequest("手机号或者验证码不能为空");
        }
        var captchaManager = HttpContext.RequestServices.GetRequiredService<ICaptchaManager>();
        if (!captchaManager.Validate(phone, code))
        {
            return ApiResponse.BadRequest("验证码无效");
        }
        var smsManager = HttpContext.RequestServices.GetRequiredService<ISmsCaptchaManager>();
        var result = await smsManager.SendAsync(phone,
            templateId,
            TimeSpan.FromMinutes(optionAccessor.Value.CaptchaExpires),
            optionAccessor.Value.CaptchaLength)
            ? ApiResponse.Ok : ApiResponse.BadRequest("发送失败");
        return result;
    }
}
